<?php
namespace App\Admin\Controllers\Shipping;

use App\Admin\Actions\Shipping\SkuBatchApproval;
use App\Admin\Actions\Shipping\SkuBatchReject;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysIArea;
use App\Models\Inventory\PublicCn;
use App\Models\Product\ProductClassify;
use App\Models\Shipping\SSku;
use App\Models\Shipping\SSkuApply;
use App\Models\SsBasic\AreaSku;
use App\Util\User;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;

class SkuApprovalController extends AdminController{

    protected $title = '提货产品审批';

    protected function grid()
    {
        $shippingDate = SSkuApply::initShippingDate();
        $grid = new Grid(new SSku());
        $grid->model()->where('status',2); //待审批
        $grid->model()->collection(function (Collection $collection) use ($shippingDate){
            foreach($collection as $index => $item) {
                $item->cnp_instant_num = PublicCn::getInstant($item->psku_id);
                $applyNum = SSkuApply::getApplyNum($item->area_id,$item->psku_id,array_key_first($shippingDate),array_key_last($shippingDate));
                $applyNumTotal = 0;
                foreach ($shippingDate as $date => $label){
                    $item->{'apply_num'.$label} = array_key_exists($date,$applyNum) ? $applyNum[$date] : 0;
                    $applyNumTotal += $item->{'apply_num'.$label};
                }
                $item->diff_num = ($item->stock->cn_transit_num ?? 0) - $applyNumTotal;
//                $item->shipping_factor = SSku::getShippingFactor($item,$item->cnp_instant_num,$applyNumTotal);
            }
            return $collection;
        });
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('area.area','站点');
        $grid->column('sku.psku_code','SKU');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('area_sku.type','来源')->display(function ($value){
            return $value ? AreaSku::$_type[$value] : '';
        });
        $grid->column('skuClassify.title','品类');
        $grid->column('_avg.avg3','3天AVG')->default(0);
        $grid->column('_avg.avg7','7天AVG')->default(0);
        $grid->column('_avg.avg15','15天AVG')->default(0);
        $grid->column('_avg.avg30','30天AVG')->default(0);
        $grid->column('_avg.avg','AVG')->default(0);
        $grid->column('stock.fba_instant_num','FBA在库')->default(0);
        $grid->column('stock.fba_transit_num','FBA在途')->default(0);
        $grid->column('cnp_instant_num','公共在库')->default(0);
        $grid->column('stock.cn_instant_num','国内在库')->default(0);
        $grid->column('stock.cn_transit_num','国内在途')->default(0);
        $grid->column('stock.os_instant_num','海外仓在库')->default(0);
        $grid->column('stock.os_transit_num','海外仓在途')->default(0);
        $grid->column('purchase_cycle','生产周期');
        $grid->column('air_day','空运时效');
        $grid->column('sea_day','海运时效');
        $grid->column('air_factor','空运提货库存系数')->view('shipping.sku.factor')->help('安全系数和目前系数');
        $grid->column('sea_factor','海运提货库存系数')->view('shipping.sku.factor')->help('安全系数和目前系数');
        foreach ($shippingDate as $label){
            $grid->column('apply_num'.$label,$label.'需求');
        }
        $grid->column('diff_num','差值')->help('在途数量-提货总数');
//        $grid->column('shipping_factor','提货系数');
        $grid->column('seller_id','销售员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('is_lock','锁状态')->display(function ($value){
            return SSku::$_isLock[$value];
        });
        $grid->column('status','状态')->display(function ($value){
            return SSku::$_status[$value];
        });
        $grid->batchActions(function ($batch) {
            $batch->disableDelete();
            $batch->add(new SkuBatchReject()); //拒绝
            $batch->add(new SkuBatchApproval()); //通过
        });
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('shipping/sku-approval-download'));
        });
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->fixColumns(4,-2);
        $grid->paginate(10);
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('area_id','站点')->select(SysIArea::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('seller_id', '提货员')->select(User::getUserOptions());
                $filter->equal('area_sku.type', '来源')->select(AreaSku::$_type);
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = SSku::query()->where('status',2)->orderBy('id', 'DESC'); //待审批
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'area_sku'){
                $query->whereHas('area_sku', function ($query) use($_filter){
                    $query->where('type', $_filter['type']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if(in_array($key,['area_id','seller_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $shippingDate = SSkuApply::initShippingDate();
        SSku::exeDownload($query,$shippingDate);
    }
}
